package com.topnav.mc.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.js.lib.annotation.ApiLogger;
import com.js.lib.result.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.topnav.mc.admin.entity.SystemConfig;
import com.topnav.mc.admin.service.ISystemConfigService;
import com.topnav.mc.base.CurdController;

import io.swagger.annotations.Api;

import java.util.*;

@Api(value = "admin/sys-config", tags = "系统设置管理")
@RestController
@CrossOrigin
@RequestMapping("admin/sys-config")
public class SystemConfigController extends CurdController<SystemConfig, ISystemConfigService> {
    @Autowired
    private ISystemConfigService systemConfigService;

    @ApiLogger(apiName="/findAll")
    @ApiOperation(value = "查询所有并封装为map")
    @PostMapping("/findAll")
    @ResponseBody
    public Result findAll(){
        Map<String,String> data = new HashMap<String,String>();
        List<SystemConfig> list = systemConfigService.list();
        for(SystemConfig s : list){
            data.put(s.getSysKey(),s.getSysValue());
        }
        return Result.ok(data);
     }

    @ApiLogger(apiName="/updateAll")
    @ApiOperation(value = "更新所有")
    @PostMapping("/updateAll")
    @ResponseBody
    public Result updateAll(@RequestBody Map<String,String> param){

        for (Map.Entry<String,String> e : param.entrySet()){
            QueryWrapper<SystemConfig> wrapper = new  QueryWrapper<SystemConfig>().eq("sys_key",e.getKey());

            SystemConfig systemConfig = systemConfigService.getOne(wrapper,false);
            if (systemConfig == null){
                systemConfig = (SystemConfig) new SystemConfig().setSysKey(e.getKey()).setSysValue(e.getValue()).setCreateTime(new Date()).setUpdateTime(new Date());
                systemConfigService.save(systemConfig);
            }else{
                systemConfig.setSysValue(e.getValue()).setUpdateTime(new Date());
                systemConfigService.updateById(systemConfig);
            }
        }
        return Result.ok();
    }


}
